package com.dyp.content_negotiation.configuration;

import com.dyp.content_negotiation.model.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration
public class PlainTextConverterConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new  AbstractHttpMessageConverter<User>(MediaType.TEXT_PLAIN) {
            @Override
            protected boolean supports(Class<?> clazz) {
                return User.class.isAssignableFrom(clazz);
            }
            @Override
            protected User readInternal(Class<? extends User> clazz, HttpInputMessage inputMessage) {
                throw new UnsupportedOperationException();
            }
            @Override
            protected void writeInternal(User user, HttpOutputMessage outputMessage) throws IOException {
                String text = String.format("Name:%s,  Address:%s", user.getName(),  user.getName());
                outputMessage.getBody().write(text.getBytes(StandardCharsets.UTF_8));
            }
        });
    }
}
